/**
 * 莱卡 IC卡模块(M2)发卡页面实现
 */

class LK_ICCardForSave extends React.Component {
    constructor(props) {
        super(props);

        this.defaultSection = 14;
        this.ownerSelected = {};
        this.state = {
            owners: [''],
            perms: [],
            cardInfo: {},
            devNum: 0,
            staffNodes : null
        };
    }

    componentDidMount() {
        this.cardObj = lk_init((event)=>{this.socketEventCallback(event)});
    }

    socketEventCallback(event){
        if(event === "error"){
            this.downloadPlugins("检测到IC卡本地服务未运行，需要下载并安装服务才能正常使用，确认要下载么?<br>" +
                "<p style='color:red'>下载完成后，请重新刷新浏览器</p>");
        }
    }

    /**
     * 读取卡号,同时从卡信息中保存业主相关信息
     * @param type
     */
    readCardNo(type) {
        let isConected = this.cardObj.connected();
        if (!isConected) {
            layui.layer.alert("发卡器未连接");
            return;
        }

        this.cardObj.readCardNo((cardNo)=>{
            if (!cardNo)
                layui.layer.alert("未读到卡号");
            else {
                this.refs[type + 'CardNo'].value = cardNo;
                postJson("/card/findCard.x", {cardNo: cardNo}, (data) => {
                    this.sp = data.data.sp;
                    let cardInfo = data.data.cardInfo;
                    if (cardInfo) {
                        this.ownerSelected.ownerCode = cardInfo.ownerCode;
                        this.ownerSelected.ownerName = cardInfo.ownerName;
                        this.ownerSelected.roomInfoNum = cardInfo.roomName;
                        this.ownerSelected.commCode = cardInfo.commCode;
                        this.refs[type+'Date'].value = cardInfo.endDate?cardInfo.endDate.substr(0,10):'';
                        if (cardInfo.cardType == 's') {
                            this.refs.scommSelect.commCode = cardInfo.commCode;
                            this.refs.staffName.value = cardInfo.ownerName;
                        }
                    }
                    this.setState({
                        ownerStr: data.data.ownerStr,
                        perms: data.data.cardPerms,
                        cardInfo: cardInfo ? cardInfo : {}
                    })
                    this.cardStateCheck(type);
                })
            }
        });

    }


    resumeCard(type) {
        layui.layer.confirm("确定要恢复此卡么?",(index)=>{
            if (!this.refs[type + 'CardNo'].value) {
                layui.layer.alert("请先读取卡", {icon: 5});
                return;
            }

            if (type == 'super' && (!this.refs.scommSelect.commCode)) {
                layui.layer.alert("请选择小区", {icon: 5});
                return;
            }

            this.cardObj.setSecurtyKey(this.sp + this.getCommCode(type),()=>{
                this.cardObj.resumeCard((data)=>{
                    if(data){
                        layui.layer.alert(data);
                    }else{
                        let param = {cardNo: this.refs[type + 'CardNo'].value};
                        postJson("/card/resumeCard.x", param, function () {
                            layui.layer.alert("卡恢复成功!");
                        })
                    }
                });
            });
            layui.layer.close(index);
        });
    }

    selectOwnerDlg() {
        if (!this.cardStateCheck("normal")) return;
        this.refs.selectOwner.show();
    }

    selectDevDlg() {
        if (!this.cardStateCheck("normal")) return;

        this.refs.selectDev.show();
    }

    onChangeRoom() {
        let commSelect = this.refs.commSelect;
        let roomInfoNum = commSelect.commCode + commSelect.buildingCode + commSelect.unitCode + commSelect.floorCode + commSelect.roomCode;

        postJson("/owner/findOwnerByRoom.x", {roomCode: roomInfoNum}, (data) => {
            this.setState({owners: data.data});
        })
    }

    onChangeUnit() {
        if (!this.refs.devSelect.unitCode)
            return;
        let params = {
            commCode: this.refs.devSelect.commCode,
            buildingCode: this.refs.devSelect.buildingCode,
            unitCode: this.refs.devSelect.unitCode
        }

        postJson("/building/getUnitDevNum.x", params, (data) => {
            this.setState({devNum: data.data});
        })
    }

    selectOwner() {
        let ownerCode = this.refs.ownerSelect.value;
        for (let i = 0; i < this.state.owners.length; i++) {
            if (ownerCode == this.state.owners[i].ownerCode) {
                this.ownerSelected = this.state.owners[i];
                this.state.ownerStr = this.ownerSelected.roomInfo + " " + this.ownerSelected.ownerName;
                break;
            }
        }

        if (this.refs.defaultPerms.checked) {
            let param = {ownerCode: this.ownerSelected.ownerCode};
            postJson("/card/getDefaultPerms.x", param, (data) => {
                this.setState({perms: data.data});
                this.refs.selectOwner.close();
            })
        } else {
            this.refs.selectOwner.close();
            this.setState({perms: ['']});
        }

        return false;
    }

    /* 将设备号转换为IC卡权限设备号 ,由于IC卡内部使用2个字节表示一个设备号,因此将16个字节拆分成3个区域
			栋数  - 单元号 - 设备号
			9字节      4字节        3字节

			因此可以支持512栋， 每栋16单元，每单元8个设备 .
			围墙机号码,使用栋数单元数为0即可
		*/
    getDevNumber(areaCodeInt, buildingCodeInt, devNumInt) {
        let result = (areaCodeInt << 7) | (buildingCodeInt << 3) | devNumInt;
        let resultStr = result.toString(16);

        if (resultStr.length == 2)
            resultStr = "00" + resultStr;
        else if (resultStr.length == 3)
            resultStr = "0" + resultStr;

        return resultStr;
    }

    addNewPerms(perm) {
        for (let i = 0; i < this.state.perms.length; i++) {
            if (this.state.perms[i].devBuildingNo == perm.devBuildingNo)
                return;
        }

        this.state.perms.push(perm);
    }

    selectDev() {
        let areaCodeInt = this.refs.devSelect.buildingCode;
        let buildingCodeInt = this.refs.devSelect.unitCode;
        let devNumInt = this.state.devNum;
        for (let i = 1; i <= devNumInt; i++) {
            let perm = {};
            perm.devNo = this.getDevNumber(areaCodeInt, buildingCodeInt, i);
            perm.devStr = '[' + this.refs.devSelect.commText + "] " + this.refs.devSelect.buildingText + " " + this.refs.devSelect.unitText + " " + i + "号机 ";
            perm.devBuildingNo = this.refs.devSelect.commCode + this.refs.devSelect.buildingCode + this.refs.devSelect.unitCode + "000" + i;
            this.addNewPerms(perm);
        }

        this.setState({perms: this.state.perms});
        this.refs.selectDev.close();
        return false;
    }

    removePerm(index) {
        this.state.perms.splice(index, 1);
        this.setState({perms: this.state.perms});
    }

    cardStateCheck(type) {
        if (type == "normal" && this.state.cardInfo.cardType == "s") {
            layui.layer.alert("检测到此卡已发布为超级卡,请去超级卡页面操作！", {icon: 0});
            return false;
        } else if (type == "super" && this.state.cardInfo.cardType == "n") {
            layui.layer.alert("检测到此卡已发布为普通卡,请去普通卡页面操作！", {icon: 0});
            return false;
        }
        return true;
    }

    getCommCode(type) {
        if (type == 'super')
            return this.refs.scommSelect.commCode;

        if (this.ownerSelected.commCode)
            return this.ownerSelected.commCode;
        else if (this.refs.scommSelect.commCode)
            return this.refs.scommSelect.commCode;
        else
            return this.state.cardInfo.commCode;
    }

    /**
     * 发普通卡
     * @returns {boolean}
     */
    publishNormalCard() {
        if (!this.cardStateCheck("normal")) return;
        if (!this.state.ownerStr) {
            layui.layer.alert("请选择业主");
            return;
        }
        if (this.state.perms.length == 0) {
            layui.layer.alert("请选择权限");
            return;
        }

        if (this.state.perms.length > 8) {
            layui.layer.alert("目前一张卡只能支持8个门!", {icon: 5});
            return;
        }


        let cardperm = "";
        for (let i = 0; i < this.state.perms.length; i++)
            cardperm += this.state.perms[i].devNo;

        this.writeCard(cardperm,0,this.refs.normalCardNo.value,"normal",()=>{
            let params = {
                ownerCode: this.ownerSelected.ownerCode,
                ownerName: this.ownerSelected.ownerName,
                roomName: this.ownerSelected.roomInfoNum,
                commCode: this.ownerSelected.commCode,
                cardType: 'n',
                nState: '01',
                nCardNo: this.refs.normalCardNo.value,
                endDate : this.refs.normalDate.value,
                permsStr: []
            };

            for (let i = 0; i < this.state.perms.length; i++)
                params.permsStr[i] = ('x:' + this.state.perms[i].devNo + ":" + this.state.perms[i].devStr + ":" + this.state.perms[i].devBuildingNo);

            postAJson("/card/save.x", params, (data) => {
                layer.msg("发卡成功!");
            })
        });

        return false;
    }

    /**
     * 发超级卡
     * @returns {boolean}
     */
    publishSuperCard() {
        if (!this.refs.scommSelect.commCode) {
            layui.layer.alert("请选择小区", {icon: 5});
            return;
        }

        this.writeCard("",1,this.refs.superCardNo.value,'super',()=>{
            let params = {
                ownerCode: "",
                ownerName: this.refs.staffName.value,
                roomName: "",
                cardType: 's',
                sState: '01',
                commCode: this.refs.scommSelect.commCode,
                sCardNo: this.refs.superCardNo.value,
                endDate : this.refs.superDate.value
            };

            postJson("/card/save.x", params, () => {
                layer.msg("发卡成功!");
            })
        });
        return false;
    }


    /*
     写卡权限
     password:小区密码
     permStr:卡权限数据
     */
    writeCard(permStr, type, cardno, cardType,callback) {

        let password = this.sp + this.getCommCode(cardType);

        if (password.length != 12) {
            layui.layer.alert("无效秘钥,停止发卡");
            return;
        }

        /* 先写秘钥 */
        this.cardObj.setSecurtyKey(password);

        /* 再写权限 */
        this.cardObj.writeCard(permStr, type, cardno,callback);
    }

    downloadPlugins(str) {
        layui.layer.confirm(str?str:"请问是否手动下载IC卡本地驱动组件安装?", (index) => {
            this.refs.downloadLink.click();
            layui.layer.close(index);
        })
    }

    cancel() {
        history.back(-1);
    }

    returnOld() {
        window.location.href = '/card/forSave.x?old=true';
    }

    selectStaff(){
        if(!this.state.staffNodes) {
            let commCode = this.refs.scommSelect.commCode;
            postJson("/property/org/getList.x", {commCode: commCode}, (data) => {
                let orgsData = data.data;
                postJson("/property/staff/getByComm.x", {commCode: commCode}, (data) => {
                    let staffDatas = data.data;
                    for (let i = 0; i < staffDatas.length; i++) {
                        staffDatas[i].parentId = staffDatas[i].orgId;
                        staffDatas[i].iconclass = "fa fa-user";
                        staffDatas[i].orgName = staffDatas[i].staffName;
                        staffDatas[i].id = staffDatas[i].orgId + "-" + staffDatas[i].staffId;
                    }

                    staffDatas.push(...orgsData);
                    let staffNodes = this.refs.staffTreeModal.getNodes(staffDatas, null, 'parentId', 'id', 'orgName');

                    this.setState({staffNodes: staffNodes},()=>{
                        this.refs.staffTreeModal.show({typeData:this.refs.staffName.inputRef})
                    });
                })

            });
        }else
            this.refs.staffTreeModal.show({typeData:this.refs.staffName.inputRef})
    }

    managerCommChange(){
        this.state.staffNodes = null;
    }

    render() {
        return (
            <div>
                <Tab titles={['新增普通卡', '新增超级卡']} type="brief">
                    <TabItem show={true}>
                        <Form size="sm">
                            <Table>
                                <tbody>
                                <tr>
                                    <td width={300}>
                                        门禁卡编号
                                    </td>
                                    <td>
                                        <Input ref="normalCardNo" lay-verify="required"
                                               style={{width: 100, marginRight: 10}}/>
                                        <Button btnType="normal" size="sm" onClick={() => this.readCardNo('normal')}>读取卡号</Button>
                                        <Button btnType="danger" size="sm" onClick={() => this.resumeCard('normal')}>恢复白卡</Button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属业主</td>
                                    <td>
                                        <Button btnType="normal" size="sm" onClick={() => this.selectOwnerDlg()}>选择业主</Button>
                                        {this.state.ownerStr ? <span className="layui-badge layui-bg-green"
                                                                     style={{marginLeft: 10}}>{this.state.ownerStr}</span> : ''}
                                    </td>
                                </tr>
                                <tr>
                                    <td>有效期至:</td>
                                    <td><DateSelect placeHolder="不填表示永久有效" ref="normalDate" min={1}></DateSelect></td>
                                </tr>
                                <tr>
                                    <td>门禁权限&nbsp;&nbsp;&nbsp;
                                        <Button className="layui-btn layui-btn-normal layui-btn-sm"
                                                onClick={() => this.selectDevDlg()}>添加</Button>
                                    </td>
                                    <td>
                                        {
                                            this.state.perms ? this.state.perms.map((perm, index) => {
                                                return (
                                                    <Item>
                                                        <Button className="layui-btn layui-btn-sm layui-btn-danger"
                                                                onClick={() => this.removePerm(index)}>删除</Button>
                                                        <span style={{marginLeft: 10}}>{perm.devStr}</span>
                                                        {index + 1 != this.state.perms.length ? <hr/> : ''}
                                                    </Item>
                                                )
                                            }) : '未查询到该卡权限'
                                        }
                                    </td>
                                </tr>
                                </tbody>
                            </Table>
                            <Button className="layui-btn" onClick={() => this.publishNormalCard()}
                                    lay-submit="true">保存</Button>
                            <Button className="layui-btn layui-btn-normal" onClick={() => this.cancel()}>取消</Button>
                        </Form>
                    </TabItem>
                    <TabItem>
                        <Form size="sm">
                            <Table>
                                <tbody>
                                <tr>
                                    <td width={300}>
                                        门禁卡编号
                                    </td>
                                    <td>
                                        <Input ref="superCardNo" lay-verify="required" style={{width: 100, marginRight: 10}}/>
                                        <Button btnType="normal" size="sm" onClick={() => this.readCardNo('super')}>读取卡号</Button>
                                        <Button btnType="danger" size="sm" onClick={() => this.resumeCard('super')}>恢复白卡</Button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属小区</td>
                                    <td>
                                        <LayuiCommSelect mask={['commCode','building', 'unit', 'floor', 'room']} ref="scommSelect" commCode={this.props.commCode}
                                                         commSelectShowStyle="BadgeWhenOneComm" onChangeComm={()=>this.managerCommChange()}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属物管员工</td>
                                    <td>
                                        <Item style={{marginBottom:0}}>
                                            <ButtonInput ref="staffName" placeHolder="默认显示为管理员" onClick={()=>this.selectStaff()} size="sm"/>
                                            <TreeModal ref="staffTreeModal" nodes={this.state.staffNodes} errorStr="未找到管理员数据<br/>请去组织人员管理中创建" onSelected={
                                                (string,data)=>{
                                                    if(data.staffId)
                                                        this.refs.staffName.value = string;
                                                    else
                                                        layui.layer.msg("请选择员工");
                                                }
                                            }/>
                                        </Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td>有效期至:</td>
                                    <td><DateSelect placeHolder="不填表示永久有效" ref="superDate" min={1}/></td>
                                </tr>
                                </tbody>
                            </Table>
                            <Button  onClick={() => this.publishSuperCard()} lay-submit="true">保存</Button>
                            <Button btnType="normal" onClick={() => this.cancel()}>取消</Button>
                        </Form>
                    </TabItem>
                </Tab>

                <Modal ref="selectOwner" title="楼栋单元选择" offset='100px' area={['1000px']}>
                    <Form size="sm">
                        <Item style={{margin: 10}}>
                            <LayuiCommSelect onChangeRoom={() => this.onChangeRoom()} commCode={this.props.commCode} mask={['commCode']}
                                             ref="commSelect"/>
                            <Select ref="ownerSelect" lay-verify="required">
                                <option value="">请选择业主</option>
                                {
                                    this.state.owners.map((owner) => {
                                        return <option value={owner.ownerCode}>{owner.ownerName}</option>
                                    })
                                }
                            </Select>
                        </Item>
                        <hr/>
                        <div style={{marginLeft: 100}}>
                            <Checkbox title="自动生成默认权限" checked={true} ref="defaultPerms"/>
                            <Button btnType="normal" size="sm" onClick={() => this.selectOwner()} lay-submit="true">确认</Button>
                        </div>
                    </Form>
                </Modal>
                <Modal ref="selectDev" title="权限选择" area={['470px']} offset="100px">
                    <Form size="sm">
                        <Item style={{margin: 10}}>
                            <LayuiCommSelect onChangeUnit={() => this.onChangeUnit()} ref="devSelect" commCode={this.props.commCode}
                                             mask={['commCode','floor', 'room']} lay-verify="required"/>
                            <Button btnType="normal" size="sm" lay-submit="true"
                                    onClick={() => this.selectDev()}>确定</Button>
                        </Item>
                    </Form>
                </Modal>
                <a target="downLoadFileFrame" hidden href="https://gerneralfiles.oss-cn-shenzhen.aliyuncs.com/manual/resource/CardDriverSetup.msi" ref="downloadLink"/>
            </div>
        )
    }
}